package com.starbaba.core.utils;

import java.net.InetAddress;
import java.net.InetSocketAddress;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IP工具类
 *
 * @Copyright: Copyright (c) 2006
 * @Company: Revenco Tech Ltd.
 * @anthor chenminhui<chenminhui@revenco.com>
 * @since 2011-7-17 上午11:32:48
 * @version V1.0
 *
 */
public class IPUtil {
	
	private static Logger logger = LoggerFactory.getLogger(IPUtil.class);
	
	/**
	 * 获取客户端IP地址
	 * @param address 客户端地址
	 * @return String 客户端IP地址
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2012-9-3 下午02:48:39
	 * @version V1.0
	 */
	public static String getClientIP(InetSocketAddress address) {
		if(address == null)	return null;
		
		return getClientIP(address.getAddress());
	}
	
	/**
	 * 获取客户端IP地址
	 * @param address 客户端地址
	 * @return String 客户端IP地址
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2012-9-3 下午02:49:11
	 * @version V1.0
	 */
	public static String getClientIP(InetAddress address) {
		if(address == null)	return null;
		
		return address.getHostAddress();
	}
	
	/**
	 * 获取客户端IP地址
	 * @param request 客户请求request
	 * @return String 客户端IP地址
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2012-9-3 下午02:49:29
	 * @version V1.0
	 */
	public static String getClientIP(HttpServletRequest request) {
		if(request==null)	return null;
		
		String localIP = "127.0.0.1";
		
		String ip = request.getHeader("x-forwarded-for"); 
//        logger.info("x-forwarded-for,"+ip);
        if(ip == null || ip.length() == 0 || (localIP.equalsIgnoreCase(ip)) || "unknown".equalsIgnoreCase(ip)) {
        	ip = request.getHeader("Proxy-Client-IP"); 
        }
        
//        logger.info("Proxy-Client-IP,"+ip);
        if(ip == null || ip.length() == 0 || (localIP.equalsIgnoreCase(ip)) || "unknown".equalsIgnoreCase(ip)) {
        	ip = request.getHeader("WL-Proxy-Client-IP");//
        }
        
//        logger.info("WL-Proxy-Client-IP,"+ip);
        if(ip == null || ip.length() == 0 || (localIP.equalsIgnoreCase(ip)) || "unknown".equalsIgnoreCase(ip)) {
        	ip = request.getRemoteAddr();
        }
        
//        logger.info("RemoteAddr,"+ip);
        if (StringUtils.isBlank(ip)){
        	logger.warn("IP cannot getted!");
        }
         
		return ip;
	}

}
